package com.lcf.system.manager;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.exception.SysException;
import com.lcf.system.entity.SysRole;
import com.lcf.system.entity.SysTenant;
import com.lcf.system.entity.SysTenantUser;
import com.lcf.system.entity.SysUserRole;
import com.lcf.system.enums.SysRoleEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 描述：租户
 *
 * @author lcf
 * @since 2025/3/3 14:10
 */
@Component
public class SysTenantManager {
    /**
     * 用户退出租户
     */
    public void quit(long tenantId, long userId) {
        checkOnlyOneAdmin(tenantId, userId);

        Db.lambdaUpdate(SysTenantUser.class)
                .eq(SysTenantUser::getTenantId, tenantId)
                .eq(SysTenantUser::getUserId, userId)
                .remove();

        Db.lambdaUpdate(SysUserRole.class)
                .eq(SysUserRole::getTenantId, tenantId)
                .eq(SysUserRole::getUserId, userId)
                .remove();
    }

    /**
     * 检查是否存在
     */
    public void checkExist(Long id, String tenantName) {
        if (StringUtils.isBlank(tenantName)) {
            return;
        }

        boolean exists = Db.lambdaQuery(SysTenant.class)
                .ne(id != null, SysTenant::getId, id)
                .eq(StringUtils.isNotBlank(tenantName), SysTenant::getTenantName, tenantName)
                .exists();
        if (exists) {
            throw new SysException("名称已存在");
        }
    }

    /**
     * 检查是否只剩一个租户管理员
     */
    private void checkOnlyOneAdmin(long tenantId, long userId) {
        //检查是否还有至少一个租户管理员
        SysRole adminRole = Db.lambdaQuery(SysRole.class)
                .eq(SysRole::getRoleCode, SysRoleEnum.ADMIN.getCode())
                .eq(SysRole::getTenantId, tenantId)
                .one();
        if (adminRole == null) {
            return;
        }

        List<SysUserRole> list = Db.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getRoleId, adminRole.getId())
                .eq(SysUserRole::getTenantId, tenantId)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        if (list.stream().allMatch(x -> Objects.equals(x.getUserId(), userId))) {
            throw new SysException("至少保留一位管理员");
        }
    }
}
